package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedList;
import java.util.List;
import java.util.Set;


@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void save(DishDTO dishDTO) {

    }

    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        //删除菜品缓存数据
        String key="dish_"+dishDTO.getCategoryId();
        redisTemplate.delete(key);


        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //向菜品表中插入一条数据
        dishMapper.insert(dish);
        //向口味表中插入n条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        Long dishId = dish.getId();
        if(flavors!=null && flavors.size()>0){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page=dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }
    @Transactional
    @Override
    public void deleteBatch(List<Long> ids) {

        //删除菜品缓存数据
        cleanCache("dish_*");


        //判断菜品是否能够删除-----是否存在起售中
        for (Long id : ids) {
            Dish dish=dishMapper.getById(id);
            if(dish.getStatus()== StatusConstant.ENABLE){
                //当前菜品处于起售中
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //判断当前菜品是否能够删除----是否关联套餐
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if(setmealIds != null && setmealIds.size() > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //删除菜品表中的菜品数据
//        ids.forEach(id->{
//            dishMapper.deleteById(id);
//            //删除口味表中的口味
//            dishFlavorMapper.deleteByDishId(id);
//        });

        //批量删除菜品数据
        dishMapper.deleteByIds(ids);
        dishFlavorMapper.deleteByDishIds(ids);
    }

    @Override
    public DishVO getByIdWithFlavors(Long id) {
        //根据Id查询菜品数据
        Dish dish = dishMapper.getById(id);
        //查询口味数据
        List<DishFlavor> flavors = dishFlavorMapper.getByDishId(id);

        //数据封装到Vo中
        DishVO dishVO=new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(flavors);
        return dishVO;
    }

    @Transactional
    @Override
    public void updateWithFlavors(DishDTO dishDTO) {

        //删除所有菜品缓存数据
        cleanCache("dish_*");

        log.info("更新菜品{}",dishDTO);
        //修改菜品基本信息
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);
        //删除原来口味数据
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        //重新插入表口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        Long dishId = dishDTO.getId();
        if(flavors!=null && flavors.size()>0){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    @Override
    public void startOrstop(Integer status, Long id) {


        //删除菜品缓存数据
        cleanCache("dish_*");


        Dish dish=new Dish();
        dish.setId(id);
        dish.setStatus(status);
        dishMapper.update(dish);
    }
    @Override
    public List<DishVO> list(Long categoryId) {


        //查询redis是否存在缓存数据
        String key="dish_"+categoryId;
        //如果存在，直接返回
        List<DishVO> redisList = (List<DishVO>) redisTemplate.opsForValue().get(key);
        if(redisList!=null&&redisList.size()>0){
            redisTemplate.opsForValue().set(key,redisList);
            return redisList;
        }
        List<Dish> list = dishMapper.list(categoryId);
        List<DishVO> dishVoList=new LinkedList<>();
        list.forEach(dish -> {
            DishVO dishVO=new DishVO();
            BeanUtils.copyProperties(dish,dishVO);
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(dish.getId());
            dishVO.setFlavors(flavors);
            dishVoList.add(dishVO);
        });
        redisTemplate.opsForValue().set(key,list);
        return dishVoList;
    }
    private void cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

}
